/*
 * API请求封装（带验证信息）
 * config.history: [必填]用于页面跳转等逻辑
 * config.method: [必须]请求method
 * config.url: [必须]请求url
 * config.data: 请求数据
 * config.formData: 是否以formData格式提交（用于上传文件）
 * config.success(res): 请求成功回调
 * config.fail(err): 请求失败回调
 * config.done(): 请求结束回调
 */
import axios from 'axios'
import { setCookies, getCookies } from '@libs/storage'
import { store } from '@/reducer'
import { setToken } from '@/reducer/getters/user'
import { message } from 'antd'
import { globalConfig } from '@/globalConfig'

const request = axios.create({
	baseURL: globalConfig.baseUrl,
	timeout: 100000
})

//拦截请求
request.interceptors.request.use(config => {
	const TOKEN = getCookies()
	const url = config.url
	// config.baseURL = ['/GetProject', '/gettime'].includes(url) ? 'https://192.168.31.21' : globalConfig.devUrl
	if (config.method === 'get') {
		if (url.indexOf('?') === -1) {
			const params = config.params || {}
			config.params = ['/gettime'].includes(url) ? { ...params } : { ...params, TOKEN }
			config.url = ['/gettime'].includes(url) ? url : url + `&TOKEN=${TOKEN}&_=` + new Date().getTime()
		}
	}
	if (config.method === 'post') {
		const data = config.data || {}
		config.data = ['/GetProject'].includes(url) ? { ...data } : { ...data, TOKEN }
	}
	if (url === '/apilogin') {
		config.headers['Authorization'] = globalConfig.Authorization
	}
	return config
})

//拦截响应
request.interceptors.response.use(
	response => {
		const url = response.config.url
		const {
			data: { CODE, TOKEN }
		} = response
		if (response && response.status === 200) {
			if (url === '/gettime') {
				return Promise.resolve(response.data)
			}
			if (CODE === 1) {
				store.dispatch(setToken(TOKEN))
				setCookies(TOKEN)
				return Promise.resolve(response.data)
			} else {
				const {
					data: { MSG }
				} = response
				message.error(MSG)
				if ([103, 104, 204].includes(CODE)) {
					return Promise.resolve({})
				} else {
					return Promise.resolve({})
				}
			}
		} else {
			message.error(response.message)
			return Promise.reject(response.message)
		}
	},
	function (error) {
		//对响应的错误做点什么
		message.error(error.message)
		return Promise.reject(error)
	}
)

export default request
